//
// Created by dong on 2025/10/21.
//

#include "SEdit.h"
#include "Swindow.h"
#include "SPaint.h"

SEdit::SEdit(int x, int y)
{
    m_data->x = x;
    m_data->y = y;
    isInput=false;
    isEdit = false;
}

void SEdit::paintEvent(SDL_Event* msg)
{
    if (isInput==true)
    {
        m_data->curColor={200,200,255,0};
    }else
    {
        m_data->curColor={238,238,242,0};
    }
    Swidget::paintEvent(msg);

    if (!m_input.empty())
    {
        // TTF_Font* font = TTF_OpenFont("../simkai.ttf",20);
        // SDL_Surface* surface = TTF_RenderUTF8_Blended(font,m_input.c_str(),m_data->textColor);
        // SDL_Texture* temp = SDL_CreateTextureFromSurface(Swindow::render,surface);
        // SDL_Rect dst = {m_data->x+10,m_data->y+(m_data->h-surface->h)/2,surface->w,surface->h};
        // SDL_RenderCopy(Swindow::render,temp,NULL,&dst);
        // SDL_FreeSurface(surface);
        // SDL_DestroyTexture(temp);
        // TTF_CloseFont(font);
        SPaint paint;
        paint.drawText(m_data->x+10,m_data->y,m_input.c_str());
    }
}

void SEdit::mousePressEvent(SDL_Event* msg)
{
    if (Swidget::contains(msg->motion.x,msg->motion.y))
    {
        isInput=true;
        m_data->isFocus=true;
    }else
    {
        isInput=false;
        m_data->isFocus=false;
    }
}

void SEdit::inputEvent(SDL_Event* msg)
{
   if (isInput==true){}
    m_input+=msg->text.text;
}

void SEdit::editEvent(SDL_Event* msg)
{
   string curStr = msg->edit.text;
    if (!curStr.empty() && isInput)
    {
        // TTF_Font* font = TTF_OpenFont("../simkai.ttf",20);
        // SDL_Surface* surface = TTF_RenderUTF8_Blended(font,curStr.c_str(),m_data->textColor);
        // SDL_Texture* temp = SDL_CreateTextureFromSurface(Swindow::render,surface);
        // SDL_Rect dst = {m_data->x+50,m_data->y+m_data->h+10,surface->w,surface->h};
        // SDL_RenderCopy(Swindow::render,temp,NULL,&dst);
        // SDL_FreeSurface(surface);
        // SDL_DestroyTexture(temp);
        // TTF_CloseFont(font);

        SPaint paint;
        paint.drawText(m_data->x+50,m_data->y+m_data->h+10,curStr.c_str());
    }
}

void SEdit::keyDownEvent(SDL_Event* msg)
{
  if (!m_input.empty())
  {
      if (msg->key.keysym.sym=='\b')
      {
          size_t pos = m_input.size()-1;
          if (m_input.at(pos)>=0)
          {
              m_input.erase(pos);
          }else
          {
              m_input.erase(pos);
              m_input.erase(pos-1);
              m_input.erase(pos-2);
          }

      }
  }
}
